import math
from datetime import time

import pyautogui
import uiautomation as auto
import os
# import AutoIt

from pyautogui import *
from PIL import Image
import numpy as np
from paddleocr import PaddleOCR, draw_ocr


def get_curtime(time_format="%Y-%m-%d %H:%M:%S"):
    curTime = time.localtime()
    curTime = time.strftime(time_format, curTime)
    return curTime


def ocr_get_txt_pos(path="", text=""):
    '''
    获取文字与位置对应map
    :param path:图片路径，图片路径为空则默认获取当前屏幕截图
    :param text: 筛选需要查找的内容，匹配所有位置
    :return:list
    '''

    result, img_path = ocr_img_text(path, saveimg=True)

    print("图片识别结果保存：", img_path)

    poslist = [detection[0][0] for line in result for detection in line]
    txtlist = [detection[1][0] for line in result for detection in line]

    # 用list存文字与位置信息
    find_txt_pos = []

    items = 0

    if text == "":
        find_txt_pos = result
    else:
        for i in range(len(poslist)):
            if txtlist[i] == text or text in txtlist[i]:
                find_txt_pos.append(poslist[i])
                items += 1

    print(find_txt_pos)
    return find_txt_pos

#获取左下角的角标
def ocr_get_txt_pos_three(path="", text=""):
    '''
    获取文字与位置对应map
    :param path:图片路径，图片路径为空则默认获取当前屏幕截图
    :param text: 筛选需要查找的内容，匹配所有位置
    :return:list
    '''

    result, img_path = ocr_img_text(path, saveimg=True)

    print("图片识别结果保存：", img_path)

    poslist = [detection[0][2] for line in result for detection in line]
    txtlist = [detection[1][0] for line in result for detection in line]

    # 用list存文字与位置信息
    find_txt_pos = []

    items = 0

    if text == "":
        find_txt_pos = result
    else:
        for i in range(len(poslist)):
            if txtlist[i] == text or text in txtlist[i]:
                find_txt_pos.append(poslist[i])
                items += 1

    print(find_txt_pos)
    return find_txt_pos

#有些ocr识别有点不准确使用右角标位置
def ocr_get_txt_pos_right(path="", text="", ref=""):
    '''
    获取文字与位置对应map
    :param path:图片路径，图片路径为空则默认获取当前屏幕截图
    :param text: 筛选需要查找的内容，匹配所有位置
    :param ref: 参考对象
    :return:list
    '''

    result, img_path = ocr_img_text(path, saveimg=True)

    print("图片识别结果保存：", img_path)

    poslist = [detection[0][1] for line in result for detection in line]
    txtlist = [detection[1][0] for line in result for detection in line]

    # 用list存文字与位置信息
    find_txt_pos = []
    find_txt_pos_ref = []

    items = 0

    if text == "":
        find_txt_pos = result
    elif ref == "":
        for i in range(len(poslist)):
            if txtlist[i] == text or text in txtlist[i]:
                find_txt_pos.append(poslist[i])
                items += 1
    else:
        # 获取参考对象的坐标
        for i in range(len(poslist)):
            if txtlist[i] == ref or ref in txtlist[i]:
                find_txt_pos_ref.append(poslist[i])
                print(poslist[i])
        # 获取需要点击的坐标
        for i in range(len(poslist)):
            if (txtlist[i] == text or text in txtlist[i]) and (poslist[i][1] < find_txt_pos_ref[0][1] + 20):
                find_txt_pos.append(poslist[i])
                print(poslist[i])
                items += 1

    print(find_txt_pos)
    return find_txt_pos

#专门用于用于点击进入应用的地址
def ocr_get_txt_pos_modify(path="", text=""):
    '''
    获取文字与位置对应map
    :param path:图片路径，图片路径为空则默认获取当前屏幕截图
    :param text: 筛选需要查找的内容，匹配所有位置
    :return:list
    '''

    result, img_path = ocr_img_text(path, saveimg=True)

    print("图片识别结果保存：", img_path)

    poslist = [detection[0][0] for line in result for detection in line]
    poslistEnd = [detection[0][1] for line in result for detection in line]
    txtlist = [detection[1][0] for line in result for detection in line]

    # 用list存文字与位置信息
    find_txt_pos = []

    items = 0

    if text == "":
        find_txt_pos = result
    else:
        for i in range(len(poslist)):
            if txtlist[i] == text or text in txtlist[i]:
                find_txt_pos.append(poslist[i])
                find_txt_pos.append(poslistEnd[i])
                items += 1

    print(find_txt_pos)
    return find_txt_pos

#使用两个元素的比例来确定位置
def ocr_get_txt_pos_prop(path="", text="固定", fromText="", endText=""):
    '''
    获取文字与位置对应map
    :param path:图片路径，图片路径为空则默认获取当前屏幕截图
    :param text: 筛选需要查找的内容，匹配所有位置
    :param fromText: 筛选需要查找的内容，匹配所有位置
    :param endText: 筛选需要查找的内容，匹配所有位置
    :return:list
    '''

    result, img_path = ocr_img_text(path, saveimg=True)

    print("图片识别结果保存：", img_path)

    poslist = [detection[0][0] for line in result for detection in line]
    # poslistEnd = [detection[0][1] for line in result for detection in line]
    txtlist = [detection[1][0] for line in result for detection in line]

    # 用list存文字与位置信息
    find_txt_pos = []
    # find_txt_pos_end = []

    items = 0

    if text == "":
        find_txt_pos = result
    else:
        for i in range(len(poslist)):
            #两个元素必须相邻位置
            if (txtlist[i] == fromText or fromText in txtlist[i]) and (txtlist[i + 2] == endText or endText in txtlist[i + 2]):
                find_txt_pos.append(poslist[i])
                find_txt_pos.append(poslist[i + 2])
                items += 1

    print(find_txt_pos)
    return find_txt_pos

#识别图片文字
# def ocr_img_text(path="", saveimg=False, printResult=False):
#     '''
#     图像文字识别
#     :param path:图片路径
#     :param saveimg:是否把结果保存成图片
#     :param printResult:是否打印出识别结果
#     :return:result,img_name
#     '''
#     image = path
#
#     # 图片路径为空就默认获取屏幕截图
#     if image == "":
#         image = screenshot()
#         image = np.array(image)
#     else:
#         # 不为空就打开
#         image = Image.open(image).convert('RGB')
#
#     ocr = PaddleOCR(use_angle_cls=True, lang="ch")  # need to run only once to download and load model into memory
#
#     result = ocr.ocr(image, cls=True)
#     if printResult is True:
#         for line in result:
#             for word in line:
#                 print(word)
#
#     # 识别出来的文字保存为图片
#     img_name = "ImgTextOCR-img-" + get_curtime("%Y%m%d%H%M%S") + ".jpg"
#     if saveimg is True:
#         boxes = [detection[0] for line in result for detection in line]  # Nested loop added
#         txts = [detection[1][0] for line in result for detection in line]  # Nested loop added
#         scores = [detection[1][1] for line in result for detection in line]  # Nested loop added
#         im_show = draw_ocr(image, boxes, txts, scores)
#         im_show = Image.fromarray(im_show)
#         im_show.save(img_name)
#
#     return result, img_name

def ocr_img_text(path="", saveimg=False, printResult=False):
    '''
    图像文字识别
    :param path: 图片路径，为空则默认获取当前屏幕截图
    :param saveimg: 是否保存识别结果为图片
    :param printResult: 是否打印识别结果
    :return: 识别结果, 保存的图片名称
    '''
    # 初始化变量
    img_data = None
    img_name = "ImgTextOCR-img-" + get_curtime("%Y%m%d%H%M%S") + ".jpg"
    ocr_result = []
    boxes, txts, scores = [], [], []

    try:
        # 图片路径为空则默认获取屏幕截图
        if not path:
            img_data = np.array(screenshot())
        else:
            # 打开并转换图片格式
            with Image.open(path) as img:
                img_data = img.convert('RGB')

        # 初始化OCR模型
        ocr = PaddleOCR(use_angle_cls=True, lang="ch")
        ocr_result = ocr.ocr(img_data, cls=True)

        # 构造boxes, txts, scores列表
        for line in ocr_result:
            for detection in line:
                boxes.append(detection[0])
                txts.append(detection[1][0])
                scores.append(detection[1][1])

        # 打印识别结果
        if printResult:
            for line in ocr_result:
                for word in line:
                    print(word)

        # 保存识别结果为图片
        if saveimg:
            im_show = draw_ocr(img_data, boxes, txts, scores)
            im_show = Image.fromarray(im_show)
            im_show.save(img_name)

    except Exception as e:
        print(f"Error occurred during OCR processing: {e}")

    finally:
        # 清理资源，如需要的话关闭图像文件等（此处已使用with语句自动管理）
        pass

    return ocr_result, img_name

#获取坐标
def getCoordinate(text="", type="", endText="", prop=0.000001, ref=""):
    '''
    获取坐标
    :param text: 筛选需要查找的内容，匹配所有位置
    :param type: 类型，prop代表使用像素比例进行定位
    :param endText: text = fromText 结束文本
    :param prop: 像素比例    0.5
    :return:list
    '''
    # #获取当前界面截图元素
    # ocr_img_text(saveimg=True, printResult=True)
    #获取登录应用界面数据
    if type == "":
        if text == "172.88.1.61:89":
            pos_list = ocr_get_txt_pos_modify(text="172.88.1.61:89")
            pos_xOne, pos_yOne = pos_list[0]
            pos_xTwo, pos_yTwo = pos_list[1]
            res = [(pos_xOne + pos_xTwo) / 2, pos_yOne - 50]
            return res
        elif text == "审核":
            pos_list = ocr_get_txt_pos_right(text=text)
            pos_x, pos_y = pos_list[0]
            return [pos_x-10, pos_y+5]
        else:
            pos_list = ocr_get_txt_pos(text=text)
            pos_x, pos_y = pos_list[0]
            return [pos_x + 5, pos_y + 5]
    elif type == "right":
        pos_list = ocr_get_txt_pos_right(text=text, ref=ref)
        pos_x, pos_y = pos_list[0]
        return [pos_x, pos_y + 10]
    elif type == "prop":#使用像素比例进行定位--用于一些识别不到的符合
        pos_list = ocr_get_txt_pos_prop(fromText=text, endText=endText)
        pos_x_from, pos_y_from = pos_list[0]
        pos_x_end, pos_y_end = pos_list[1]
        return [int(math.floor((pos_x_end - pos_x_from) * prop)) + 5, pos_y_from + 5]
    else:
        pass





if __name__ == '__main__':
    # print("业务会计" in "业务会")
    # test-1
    # result, img_name = ocr_img_text(saveimg=True, printResult=True)
    # print(img_name)

    import pyperclip

    # pos = ocr_get_txt_pos_three(text="主体账簿")
    # posX, posY = pos[0]
    # X = int(math.floor(posX))
    # Y = int(math.floor(posY))
    # auto.Click(X + 5, Y + 20, waitTime = 1)


    pyautogui.keyDown('shiftleft')
    pyautogui.keyDown('shiftright')
    time.sleep(0.1)
    pyautogui.press(['down', 'down', 'down', 'down'])
    pyautogui.keyUp('shiftleft')
    pyautogui.keyUp('shiftright')
    # auto.SendKeys('{SHIFT+DOWN}')
    #点击账套
    # pos = getCoordinate("深圳华强物业管理有限公司2006会计准则账簿", type="right")
    # pos = getCoordinate("常用条件")
    # X = int(math.floor(pos[0]))
    # Y = int(math.floor(pos[1]))
    # auto.Click(X, Y, waitTime=1)
    #
    # # 输入enter事件来点击主体账簿
    # auto.SendKeys('{ENTER 7}')
    #
    # auto.SendKeys('{DOWN}')
    # auto.SendKeys('{UP}')
    # auto.SendKeys('{ENTER}')
    # auto.SendKeys('{DOWN 2}')

    # # 全选当前账套，后续要ctrl+v
    # auto.SendKeys('{Ctrl}(A)')
    #
    #
    # # 将规定复制到系统剪贴板
    # pyperclip.copy('HQA-0002,HNY-0002,HQJ-0002,HQS-0002,SCW-0002,SDX（旧）-0002,SGY-0002,SHQ-0002,SQH-0002,SQZ-0002,SSD-0002,SWY-0002,SZX-0002,YTZ-0002,ZYX-0002,HQB-0002')  # 将规定复制到系统剪贴板#
    # auto.SendKeys('{Ctrl}(V)')


    #获取密码坐标
    # res = getCoordinate("密码")
    # res1 = getCoordinate("选项《")
    # print(res)
    # print(res1)
    # moveTo(res1[0], res[1])

#
#     # test-2
#     pos_list = ocr_get_txt_pos_modify(text="172.88.1.61:89")
#
#     # test-3
#     pos_list = ocr_get_txt_pos(text="查询卡片显示")
#     pos = getCoordinate("主体账簿", type="prop", endText="制单系统", prop=0.965517)
#     pos = getCoordinate("制单系统")
#     X = int(math.floor(pos[0] + 5))
#     Y = int(math.floor(pos[1] + 5) )
#     # pyautogui.click(X, Y, clicks=2, interval=0.1, duration=3.0)
#     # auto.Click(X, Y, waitTime=1)
#     moveTo(X, Y)

    # auto.Click(X, Y, waitTime=1)
#
#     # 取一个点进行点击操作
#     pos_xOne, pos_yOne = pos_list[0]
#     pos_xTwo, pos_yTwo = pos_list[1]
#     # moveTo(pos_x + 5, pos_y + 5)
#     moveTo((pos_xOne + pos_xTwo)/2, pos_yOne - 50)
#     click()


# [[[42.0, 324.0], [130.0, 324.0], [130.0, 345.0], [42.0, 345.0]], ('凭证管理', 0.999692440032959)]
# [[[42.0, 324.0], [130.0, 324.0], [130.0, 345.0], [42.0, 345.0]], ('凭证管理', 0.9997483491897583)]
#     moveTo(27, 329)



    # The process name to be brought to an abrupt halt
    # process_name = "UClient.exe"
    #
    # # Employing the taskkill command to terminate the process
    # result = os.system(f"taskkill /f /im {process_name}")
    #
    # if result == 0:
    #     print(f"Instance deletion successful: {process_name}")
    # else:
    #     print("Error occurred while deleting the instance.")
